package com.li.algorithm.leetcode.hot100;

import java.util.HashMap;
import java.util.Stack;

public class hot_20_有效的括号 {

    public boolean isValid(String s) {
        if (s == null || s.length() % 2 == 1) {
            return false;
        }
        //TODO:后进先出，出现匹配则出队，不匹配则返回false
        HashMap<Character, Character> p = new HashMap<>();
        p.put(')', '(');
        p.put(']', '[');
        p.put('}', '{');
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            //左括号入队
            if (p.containsValue(s.charAt(i))) {
                stack.push(s.charAt(i));
            } else {
                //右括号判断是否匹配
                if (stack.isEmpty() || stack.getLast() != p.get(s.charAt(i))) {
                    return false;
                } else {
                    stack.pop();
                }
            }
        }
        return stack.isEmpty();
    }


    public static void main(String[] args) {
        hot_20_有效的括号 test = new hot_20_有效的括号();
        System.out.println(test.isValid("){"));
    }
}
